package jp.ac.utokyo.pinyomi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class KanjiReadingTable extends AbstractTable {
	private static KanjiReadingTable instance;

	private KanjiReadingTable() throws IOException {
		super();
	}

	public static synchronized KanjiReadingTable getInstance()
			throws IOException {
		if (instance == null) {
			instance = new KanjiReadingTable();
		}
		return instance;
	}

	@Override
	protected HashMap<String, Pair> readfile() throws IOException {
		System.out.println("Reading KanjiReading file ...");
		
		HashMap<String, Pair> map = new HashMap<String, Pair>();
		BufferedReader in = new BufferedReader(new InputStreamReader(
					new FileInputStream(Settings.KanjiReadingCounts), "UTF-8"));

		String fieldSep = "[ |\t]+";
		String yomiSep = ",";
		String yomiCountSep = ":";
		String strLine = null;
		
		while ((strLine = in.readLine()) != null) {
			// strLine   併  ぺい:4758,あわ:723,へい:2280
			strLine = strLine.trim();
			if (!"".equals(strLine)) {
				String[] fields = strLine.split(fieldSep);
				
				// mapkey 併
				String mapkey = fields[0];
				// yomiA {ぺい:4758,あわ:723,へい:2280}
				String[] yomiA= fields[1].split(yomiSep);
				
//				System.out.print(mapkey+"==");
//				for (String s: yomiA){
//					System.out.print(s+"-");
//				}
//				System.out.println();
				
				ArrayList<String> yomiList = new ArrayList<String>();
				ArrayList<Integer> yomiCounter = new ArrayList<Integer>();
				ArrayList<Double> yomiProb = new ArrayList<Double>();
				int totalCounter = 0;
				
				for (String yomiAndCount: yomiA){
					String[] s = yomiAndCount.split(yomiCountSep);
					yomiList.add(s[0]);
					Integer counter = new Integer(s[1]);
					yomiCounter.add(counter);
					totalCounter += counter.intValue();
				}
				
				for (Integer counter: yomiCounter){
					yomiProb.add(Math.log(counter.doubleValue()/totalCounter));
				}
				
//				System.out.print(mapkey+"==");
//				for (String s: yomiList){
//					System.out.print(s+"-");
//				}
//				for (Double s: yomiProb){
//					System.out.print(s+" ");
//				}
//				for (Integer s: yomiCounter){
//					System.out.print(s+" ");
//				}
//				System.out.println();

				Pair pair = new Pair();
				pair.addPair(yomiList, yomiProb);

				map.put(mapkey, pair);
			}
		}
		return map;
	}
}
